/*
 * Copyright (C) 2012 Damien Girard <dgirard@nativesoft.fr>
 * Copyright (C) 2012 Sebastien Baudrand <sebbaudrand@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package fr.umlv.qroxy.http;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Commons HTTP commands used by the server.
 *
 * @author Damien Girard <dgirard@nativesoft.fr>
 * @author Sebastien Baudrand <sebbaudrand@gmail.com>
 */
public enum HttpCodes {

    HTTP_ENTITY_TOO_LARGE(413, "Request Entity Too Large"),
    HTTP_BAD_REQUEST(400, "Bad Request "),
    HTTP_CLIENT_TIMEOUT(408, "Request Time-out"),
    HTTP_FORBIDDEN(403, "Forbidden"),
    HTTP_BAD_METHOD(405, "Method Not Allowed"),
    HTTP_VERSION(505, "HTTP Version Not Supported."),
    HTTP_GATEWAY_TIMEOUT(504, "Gateway Timeout."),
    HTTP_BAD_GATEWAY(502, "Bad Gateway."),
    LENGTH_REQUIRED(411, "Lenght required"),
    HTTP_SERVER_ERROR(500, "Server error"),
    HTTP_UNIMPLEMENTED(501, "Unimplemented"),
    // The ultimate error code!
    HTTP_TEAPOT(418, "I am a teapot.");
    
    private final Integer code;
    private final String description;

    private HttpCodes(int code, String description) {
        this.code = code;
        this.description = description;
    }

    public Integer getCode() {
        return code;
    }

    public String getDescription() {
        return description;
    }

    public ByteBuffer getPage() {
        StringBuilder sb = new StringBuilder();
        sb.append("HTTP/1.1 ").append(code).append(" ").append(description);
        sb.append("\r\n");
        sb.append("\r\n");
        sb.append("<html><h1>").append(code).append(" ").append(description).append("</h1></html>");
        try {
            return ByteBuffer.wrap(sb.toString().getBytes("ASCII")); // Should not fire any exception.
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(HttpCodes.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    @Override
    public String toString() {
        return "HTTP " + code + " " + description;
    }
}
